/*
 * @Date         : 2022-03-02 18:17:31
 * @LastEditors  : zu1662
 * @LastEditTime : 2022-03-03 19:44:09
 * @Description  : 面包屑组件封装
 * 
 * Copyright © 2022 by zu1662, All Rights Reserved. 
 */
import React from 'react'
import { Breadcrumb } from '@douyinfe/semi-ui'
import { useLocation } from 'react-router-dom'
import { useStore } from '@/store'
import { IRoute } from '@/types/router'
/**
 * 根据当前浏览器地址栏的路由地址，在menuConfig中查找路由跳转的路径
 * 如路由地址为/charts/keyboard,则查找到的路径为[{title: "图表",...},{title: "键盘图表",...}]
 */
const getPath = (menuList: IRoute[], pathname: string) => {
  const temppath: IRoute[] = []
  try {
    const getNodePath = (node: IRoute) => {
      temppath.push(node)
      // 找到符合条件的节点，通过throw终止掉递归
      if (node.path === pathname) {
        throw new Error('GOT IT!')
      }
      if (node.children && node.children.length > 0) {
        for (let i = 0; i < node.children.length; i++) {
          getNodePath(node.children[i])
        }
        // 当前节点的子节点遍历完依旧没找到，则删除路径中的该节点
        temppath.pop()
      } else {
        // 找到叶子节点时，删除路径当中的该叶子节点
        temppath.pop()
      }
    }
    for (let i = 0; i < menuList.length; i++) {
      getNodePath(menuList[i])
    }
  } catch (e) {
    return temppath
  }
  return temppath
}

const BreadCrumb = () => {
  const { userStore } = useStore()
  const { menus: menuList } = userStore
  const location = useLocation()
  const { pathname } = location

  // 根据当前路径获取所有的 route 数据
  let path = getPath(menuList, pathname)
  if(path) {
    const first =  path[0]
    if (first && first.path !== '/home') {
      path = [{ path: '/home', title: '首页' }].concat(path)
    }
  }else {
    path = [{ path: '/home', title: '首页' }]
  }
 
  return (
    <div className="Breadcrumb-container">
      <Breadcrumb moreType='popover'>
        {path.map(item => 
          // TODO 需要判断当前为 Hash 还是 History 模式
          <Breadcrumb.Item style={{fontSize: '14px'}} key={item.path}  href={'#' + item.path}>{item.title}</Breadcrumb.Item>
        )}
      </Breadcrumb>
    </div>
  )
}

export default BreadCrumb
